<?php
class Reports extends Controller {
	
	public function __construct()
  {
    parent::Controller();
  }

  public function index() {
  	//$this->load->view('upload_view');
  }
  
  /**
   * Returns the document types currently supported by the system.
   * @return json
   */
  public function getDocumentTypes() {
    $start  = isset($_REQUEST['start'])  ? $_REQUEST['start']  :  0;
		$count  = isset($_REQUEST['limit'])  ? $_REQUEST['limit']  : 20;
		
    $q = Doctrine_Query::create()
  			->select('d.*')
  			->from('Document d');
  			//->where($where);
  			
    	if ($sort != "") {
  		    //$query .= " ORDER BY ".$sort." ".$dir;
  		    $q->orderBy($sort.' '.$dir);
  		}
  		
  		$q->offset($start);
  		$q->limit($count);
  			
  		$results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
  		//print_r($results);
  		
  		//$total = mysql_query("SELECT COUNT(id) FROM demo WHERE ".$where);
  		$q = Doctrine_Query::create()
  			->select('COUNT(*) AS total')
  			->from('Document')
  			->where($where);
  		
  		$result = $q->fetchArray();
  		$total = $result[0]['total'];
  
  		// return response to client
  		echo json_encode(array('success' => true, 'message' => 'Datos cargardo exitosamente', 'documents' => $total, 'data' => $results));  
  }
  
  public function getDocuments($documentType = DOCUMENTTYPE_THESIS, $year = null ) {
   // collect request parameters
		$start  = isset($_REQUEST['start'])  ? $_REQUEST['start']  :  0;
		$count  = isset($_REQUEST['limit'])  ? $_REQUEST['limit']  : 20;
		$sort   = isset($_REQUEST['sort'])   ? $_REQUEST['sort']   : '';
		$dir    = isset($_REQUEST['dir'])    ? $_REQUEST['dir']    : 'ASC';
		$filters = isset($_REQUEST['filter']) ? $_REQUEST['filter'] : null;
		$documentType = isset($_REQUEST['documentType']) ? (int)$_REQUEST['documentType'] : $documentType;
		$year = isset($_REQUEST['year']) ? (int)$_REQUEST['year'] : null;
		
		// GridFilters sends filters as an Array if not json encoded
		if (is_array($filters)) {
		    $encoded = false;
		} else {
		    $encoded = true;
		    $filters = json_decode($filters);
		}
		
		// initialize variables
		$where = ' 0 = 0 ';
		$qs = '';
		
		// loop through filters sent by client
		if (is_array($filters)) {
		    for ($i=0;$i<count($filters);$i++){
		        $filter = $filters[$i];
		
		        // assign filter data (location depends if encoded or not)
		        if ($encoded) {
		            $field = $filter->field;
		            $value = $filter->value;
		            $compare = isset($filter->comparison) ? $filter->comparison : null;
		            $filterType = $filter->type;
		        } else {
		            $field = $filter['field'];
		            $value = $filter['data']['value'];
		            $compare = isset($filter['data']['comparison']) ? $filter['data']['comparison'] : null;
		            $filterType = $filter['data']['type'];
		        }
		
		        switch($filterType){
		            case 'string' : $qs .= " AND ".$field." LIKE '%".$value."%'"; Break;
		            case 'list' :
		                if (strstr($value,','))  {
		                    $fi = explode(',',$value);
		                    for ($q = 0; $q < count($fi); $q++){
		                        $fi[$q] = "'".$fi[$q]."'";
		                    }
		                    $value = implode(',',$fi);
		                    $qs .= " AND ".$field." IN (".$value.")";
		                } else {
		                    $qs .= " AND ".$field." = '".$value."'";
		                }
		            Break;
		            case 'boolean' : $qs .= " AND ".$field." = ".($value); Break;
		            case 'numeric' :
		                switch ($compare) {
		                    case 'eq' : $qs .= " AND ".$field." = ".$value; Break;
		                    case 'lt' : $qs .= " AND ".$field." < ".$value; Break;
		                    case 'gt' : $qs .= " AND ".$field." > ".$value; Break;
		                }
		            Break;
		            case 'date' :
		                switch ($compare) {
		                    //BETWEEN '2011-05-17 00:00:00' AND '2011-05-17 23:59:59';
		                    case 'eq' : $qs .= " AND ".$field." BETWEEN '".date('Y-m-d',strtotime($value))." 00:00:00' AND '".date('Y-m-d',strtotime($value))." 23:59:59'"; Break;
		                    case 'lt' : $qs .= " AND ".$field." < '".date('Y-m-d',strtotime($value))." 00:00:00'"; Break;
		                    case 'gt' : $qs .= " AND ".$field." > '".date('Y-m-d',strtotime($value))." 23:59:59'"; Break;
		                }
		            Break;
		        }
		    }
		    $where .= $qs;
		}
		
		$q = Doctrine_Query::create()
  			->select('d.*, dd.*')
  			->from('Document d')
  			->where($where)
  			->andWhere('d.documentType = ?', $documentType);
  	
  	Reports::addLeftJoinByDocumentType($q, $documentType);
  			
  	if ($sort != "") {
		    $q->orderBy($sort.' '.$dir);
		}
		
		$q->offset($start);
		$q->limit($count);
		
		//var_dump($q->getSqlQuery());
			
		$results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
		//print_r($results);
		
		//$total = mysql_query("SELECT COUNT(id) FROM demo WHERE ".$where);
		$q = Doctrine_Query::create()
			->select('COUNT(*) AS total')
			->from('Document d')
			->where($where)
  		->andWhere('d.documentType = ?', $documentType);
			
		Reports::addLeftJoinByDocumentType($q, $documentType);
			//->where($where);
		
		$result = $q->fetchArray();
		$total = $result[0]['total'];
		
    // return response to client
  	echo json_encode(array('success' => true, 'message' => 'Datos cargardo exitosamente', 'documents' => $total, 'data' => $results));
  }
  
  static private function addLeftJoinByDocumentType(&$doctrineQuery, $documentType) {
    switch ($documentType) {
      case DOCUMENTTYPE_THESIS: $doctrineQuery->leftJoin('d.thesis dd');
		  break;

      case DOCUMENTTYPE_MASTER_THESIS: $doctrineQuery->leftJoin('d.masterThesis dd');
      break;
      
      case DOCUMENTTYPE_PHD_THESIS: $doctrineQuery->leftJoin('d.phdThesis dd');
      break;
      
      case DOCUMENTTYPE_MAGAZINE_ARTICLE: $doctrineQuery->leftJoin('d.magazineArticle dd');
      break;
      
      case DOCUMENTTYPE_BOOK:  $doctrineQuery->leftJoin('d.book dd');
      break;
      
      case DOCUMENTTYPE_ENCYCLOPEDIA: $doctrineQuery->leftJoin('d.encyclopedia dd');
		  break;
    }
  }

  function getJasperReports() {
    $q = Doctrine_Query::create()
  			->select('jr.*')
  			->from('JasperReport jr');
  			
    $results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
    
    if (!empty($results)) {
      // encode the possible field to htmlentities to avoid Invalid UTF-8 sequence and to make nicer result.
      $results[0]['report_title'] = htmlentities($results[0]['report_title']);
      $results[0]['description'] = htmlentities($results[0]['description']);
    }
    
    echo json_encode(array('success' => true, 'message' => 'Datos cargardo exitosamente', 'reports' => 0, 'data' => $results));  
  }
  
  /**
   * 
   * @return unknown_type
   */
  function createJasperReportLink() {
    // used to use the class method Archivo::isAllowedExtension() 
    // and Archivo::fileUploadErrorMessage()
    require_once('archivo.php');
    
    if (!isset($_REQUEST['report_id'])) {
      $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error creando enlace jasper report!', 'errormsg' => 'Par&aacute;metro "report_id" no ha sido enviado por el cliente.')));  
      return;
    }
    
    $report_id = $_REQUEST['report_id'];
    $description = isset($_REQUEST['description']) ? $_REQUEST['description'] : null;
    
    if ($_FILES['fileupload']['error'] == UPLOAD_ERR_OK) {
      if (!Archivo::isAllowedExtension($_FILES['fileupload']['name'], array('jrxml', 'jrpxml', 'xml'))) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error', 'errormsg' => 'El archivo seleccionado no tiene una extensi&oacute;n v&aacute;lida de archivo Jasper Report XML (*.jrxml | *.xml).')));
        return false;
      }
      
      $baseTargetPath = JASPER_REPORT_UPLOADS_PATH;
      if (!file_exists($baseTargetPath)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El directorio "'.$baseTargetPath.'" no existe.')));
        return false;  
      }
      
      if (!is_writable($baseTargetPath)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El directorio "'.$baseTargetPath.'" no tiene permiso de escritura.')));
        return false;  
      }
      
  		$target_path = $baseTargetPath . basename($_FILES['fileupload']['name']);
      if (is_file($target_path)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El archivo ya existe en el servidor. Por favor, renombre el archivo he intente subirlo nuevamente.')));
        return false;  
      }
      
      // here is where the success action occur 
  		if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $target_path) ) {
  		  $jasperReport = new JasperReport();
		    $jasperReport->report_title = $report_id;
		    $jasperReport->description = $description;
		    $jasperReport->filename = $_FILES['fileupload']['name'];
    		try {
    			$jasperReport->save();
    			$output = json_encode(array('success' => true, 'filename' => $_FILES['fileupload']['name']));
    		} catch (Doctrine_Exception $e) {
    			$output = json_encode(array('success' => false, 'errors' => array('title' => 'Error creando enlace a reporte jasper!', 'errormsg' => $e->getMessage())));
    		}
  		}
  		else {
  		  $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => 'Se ha producido un error al copiar el archivo subido al servidor.')));
  		}
    }
    else {
       $errorMessage = Archivo::fileUploadErrorMessage($_FILES['fileupload']['error']);
       $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => $errorMessage)));
    }
    
		echo $output;
  }
  
  /**
   * 
   * @return unknown_type
   */
  function deleteJasperReport() {
    $id = (int)json_decode($_REQUEST['data']);
  
    $filename = JasperReport::getFilenameByJasperReport_Id($id);
    if (!$filename) {
      echo json_encode(array('success' => false, 'message' => 'Error al recuperar el nombre de archivo del reporte con id = '.$id.'.'));
      return;
    }
    
    $q = Doctrine_Query::create()
		  ->delete('JasperReport')
		  ->addWhere('id = ?', $id);
		    		
		$deleted = $q->execute();
		if( !$deleted ) {
		  echo json_encode(array('success' => false, 'message' => 'El record con Id = '.$id.' no pudo ser eliminado.'));
			return;
		}
		
    $target_path = JASPER_REPORT_UPLOADS_PATH.$filename;
    if (!is_file($target_path)) {
      echo json_encode(array('success' => false, 'message' => 'El archivo '.$filename.' no existe. Cont&aacute;cte al administrador y pregunte por este problema.'));
      return;
    }

    if (unlink($target_path)) {
      echo json_encode(array('success' => true, 'message' => 'El record fue eliminado exitosamente.'));
      return;
    }
    else {
      echo json_encode(array('success' => false, 'message' => 'El archivo '.$filename.' no pudo ser eliminado. Contacte al administrador y pregunte por este problema.'));
      return;  
    }  
  }
}